<template>
  <div class="container">
    <div class="mask">
      <div v-if="isLogin" class="login">
        <div class="title">欢迎登录</div>
        <el-form ref="loginRef" label-width="auto" :model="admin" :rules="rules">
          <el-form-item prop="name">
            <el-input v-model="admin.name" style="width: 80%" placeholder="请输入用户名">
              <template #prefix
                ><el-icon><i-ep-user /></el-icon
              ></template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="admin.password" style="width: 80%" placeholder="请输入密码" show-password>
              <template #prefix
                ><el-icon><i-ep-lock /></el-icon
              ></template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-input v-model="admin.verCode" style="width: 42%; margin-right: 10px" placeholder="请输入验证码">
              <template #prefix
                ><el-icon><i-ep-message /></el-icon
              ></template>
            </el-input>
            <img :src="captchaUrl" alt="" style="width: 140px; height: 33px" @click="updateCaptcha" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" style="width: 80%" @click="Login">登录</el-button>
          </el-form-item>

          <el-form-item>
            <el-button type="warning" style="width: 80%" @click="isLogin = false">还没有账号？点击注册</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-else class="register">
        <div class="title">欢迎注册</div>
        <el-form ref="registerRef" label-width="auto" :model="admin" :rules="rules">
          <el-form-item prop="name">
            <el-input v-model="admin.name" style="width: 80%" placeholder="请输入用户名">
              <template #prefix
                ><el-icon><i-ep-user /></el-icon
              ></template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="admin.password" style="width: 80%" placeholder="请输入密码" show-password>
              <template #prefix
                ><el-icon><i-ep-lock /></el-icon
              ></template>
            </el-input>
          </el-form-item>

          <el-form-item prop="role">
            <el-select v-model="admin.role" placeholder="请选择" size="default" style="width: 80%">
              <el-option label="超级管理员" value="0" />
              <el-option label="歌曲管理员" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" style="width: 80%" @click="Register">注册</el-button>
          </el-form-item>

          <el-form-item>
            <el-button type="warning" style="width: 80%" @click="isLogin = true">已经有账号了！点击登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import type { Admin } from './type'
import { adminLoginApi, adminRegisterApi } from '@/api/admin'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getAdminName, getAdminPassword, setAdmin } from '@/utils/admin'

// 路由器对象
const router = useRouter()

const isLogin = ref(true)

const admin = reactive<Admin>({
  name: '',
  password: '',
  role: '',
  verCode: '',
})
// 注册表单对象
const registerRef = ref()
// 登录表单对象
const loginRef = ref()
// 验证码路径
const captchaUrl = ref('')
let key = ''

onMounted(() => {
  admin.name = getAdminName()
  admin.password = getAdminPassword()
  updateCaptcha()
})

// 校验规则
const rules = {
  name: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  role: [{ required: true, message: '请选择用户注册角色', trigger: 'blur' }],
}
// 清除表单数据
const clearAdmin = () => {
  ;(admin.name = ''), (admin.password = ''), (admin.role = ''), (admin.verCode = '')
}
// 利用watch监视isLogin属性的变化决定是否清除表单数据
watch(isLogin, () => {
  clearAdmin()
  if (isLogin.value) {
    updateLoginFrom()
  }
})
// 更新登录表单信息
const updateLoginFrom = () => {
  admin.name = getAdminName()
  admin.password = getAdminPassword()
}
// 更新验证码
const updateCaptcha = () => {
  admin.verCode = ''
  key = String(Math.random())
  // console.log('第一次key:',key)
  captchaUrl.value = 'http://localhost:8080/api/captcha?key=' + key
}
// 登录
const Login = async () => {
  // 导致错误原因：更新验证码的函数得在请求发送之后才能执行，否则key【更新函数又更新了一次】与之前没更新前收集的verCode不一致
  // updateCaptcha()
  await loginRef.value.validate()
  // console.log('第二次key:', key)
  let res = await adminLoginApi(key, admin)
  // TODO:在request中分类讨论了res.code!='0'的情况，所以能到这里肯定是code='0'的，所以就不用判断了
  // if(res.code==='0'){
  //   router.replace('/')
  //   ElMessage.success(`${admin.name}登录成功`)
  // }
  router.replace('/')
  // 持久化存储用户信息【包括token】
  setAdmin(res.data)
  ElMessage.success(`${admin.name}登录成功`)
  updateCaptcha()
}
// 注册
const Register = async () => {
  await registerRef.value.validate()
  let res = await adminRegisterApi(admin)
  if (res.code === '0') {
    ElMessage.success('注册成功')
    isLogin.value = true
  }
}
</script>

<style scoped lang="scss">
.container {
  height: 100vh;
  width: 100vw;
  background: url('@/assets/images/back.jpg') no-repeat;
  background-size: cover;

  .mask {
    position: absolute;
    top: 15%;
    right: 15%;
    width: 400px;
    height: 400px;
    background-color: rgba(107, 149, 224, 0.5);
    box-shadow: 20px 20px 20px #cfcfcf;
    border-radius: 5%;

    .register {
      height: 100%;
      background-color: rgba(84, 182, 174, 0.5);
      border-radius: 5%;
    }

    .title {
      height: 100px;
      line-height: 100px;
      color: #4a5ed0;
      font-size: 30px;
      text-align: center;
    }

    .el-form {
      position: relative;
      right: -10%;
    }
  }
}
</style>
